<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Server Sent Events demo</title>
    <style>
        ul{
            list-style-type: disc;
        }
        li#tit{
            list-style-type: none;
        }
        html{
            font-size: 16px;
        }
        #crow {
            color: #000;
            font-family: consolas;
            font-weight: bold;
            font-size: 16px;
            animation: crow 0.6s linear 0s infinite;
        }

        @keyframes crow {
            from {
                opacity: 0;
            }

            to {
                opacity: 1;
            }
        }
    </style>
</head>
<body>
<ul id="status_msg">
    <li id="tit">状态：</li>
</ul>
<p>问题：写一篇描述春天的文章，原创，800字左右</p>
<div id="content_msg">
    <p>答案：</p>
</div>
<script type="application/javascript">
    const errorMsgEl = document.getElementById("status_msg");
    const contentMsgEl = document.getElementById("content_msg");
    let crowEl;
    let spanElement;
    let text = "";
    run();

    /**
     * 运行 Server-Sent Events
     */
    function run(){
        if(!window.EventSource){
            const el = document.createElement('dt');
            el.innerText = '你的浏览器不支持 Server-Sent Events'
            errorMsgEl.appendChild(el)
            return;
        }
        const source = new EventSource('/index');

        // 监听连接成功事件
        source.addEventListener('open', function (event) {
            const el = document.createElement('dt');
            el.innerText = '已连接'
            errorMsgEl.appendChild(el)
        }, false);

        // 接收消息事件
        source.addEventListener('message', function (event) {
            text += event.data;
            spanElement.innerText = text
        }, false);

        // 异常事件
        source.addEventListener('error', function (event) {
            console.log(event)
            const el = document.createElement('dt');
            el.innerText = `发生错误：`+event
            errorMsgEl.appendChild(el)
        }, false);

        // 自定义 appendP 事件
        source.addEventListener('appendP', function (event) {
            if(crowEl){
                crowEl.remove();
            }
            pElement = document.createElement('p');

            crowEl = document.createElement("label");
            crowEl.id = 'crow';
            crowEl.innerText = '|';

            spanElement = document.createElement('span');

            pElement.appendChild(spanElement);
            pElement.appendChild(crowEl);

            text = "";
            contentMsgEl.appendChild(pElement)
        }, false);

        // 自定义完成事件
        source.addEventListener('complete', function (event) {
            if(crowEl){
                crowEl.remove();
            }
            source.close();
            const el = document.createElement('dt');
            el.innerText = '连接已关闭'
            errorMsgEl.appendChild(el)
        }, false);
    }
</script>
</body>
</html>